<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:template:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="计费方式" align="center" prop="templateType">
        <template slot-scope="scope">
          <dict-tag :options="templateTypeOptions" :value="scope.row.templateType"/>
        </template>
      </el-table-column>
      <el-table-column label="编辑时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运费模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="计费方式">
          <el-radio-group v-model="form.templateType">
            <el-radio
              v-for="dict in templateTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包邮配送区域" >
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="form.freeCityList" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(city,index) in cities"  :label="city" :key="city">{{regionData[index].label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="买家家付费区域">
          <el-row>
            <el-col :span="4">
              <el-tree
                :data="form.templateDataList"
                :props="defaultProps"
                @node-click="handleNodeClick"
              >
              </el-tree>
            </el-col>
            <el-col v-if="index > -1" :span="20">
              <el-row style="align-items: center">
                <el-col :span="4" style="height:100%;background-color: #ECF8FF;color: #1890FF">
<!--                  {{ form.templateDataList[index].provinceName }}-->
                </el-col>
                <el-col :span="20">
                  <div style="margin-left: 20px">
                    <div>
                      <span>
                        <el-form-item  label-width="0" style="margin-bottom: 0;width: 12%;display: inline-block" :prop="'templateDataList.' + index + '.firstValue'"  :rules="{ required: true,pattern:/^[+]{0,1}(\d+)$/,message: '条件必须为正整数', trigger: 'blur' }">
                          <el-input  v-model="form.templateDataList[index].firstValue" placeholder="" />
                        </el-form-item>
                        {{ form.templateType =='0'?'件':'千克' }}内
                        <el-form-item  label-width="0" style="margin-bottom: 0;width: 12%;display: inline-block" :prop="'templateDataList.' + index + '.firstAmount'"  :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "格式不正确",trigger: "blur" }'>
                          <el-input  v-model="form.templateDataList[index].firstAmount" placeholder="" />
                        </el-form-item>
                        元
                      </span>
                      <span style="margin-left: 25px">
                        每增加
                        <el-form-item  label-width="0" style="margin-bottom: 0;width: 12%;display: inline-block" :prop="'templateDataList.' + index + '.otherValue'"  :rules="{ required: true,pattern:/^[+]{0,1}(\d+)$/,message: '条件必须为正整数', trigger: 'blur' }">
                          <el-input  v-model="form.templateDataList[index].otherValue" placeholder="" />
                        </el-form-item>
                        {{ form.templateType =='0'?'件':'千克' }}，
                        增加运费
                        <el-form-item  label-width="0" style="margin-bottom: 0;width: 12%;display: inline-block" :prop="'templateDataList.' + index + '.otherAmount'"  :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "格式不正确",trigger: "blur" }'>
                          <el-input  v-model="form.templateDataList[index].otherAmount" placeholder="" />
                        </el-form-item>
                        元
                      </span>

                    </div>
                    <div style="margin-top: 15px">
                      <el-checkbox v-model="form.templateDataList[index].appoint" :true-label="'0'" :false-label="'1'">指定条件包邮</el-checkbox>
                      <span style="margin-left: 20px" v-if="form.templateDataList[index].appoint == '0'">
                        满
                        <el-form-item  label-width="0" style="margin-bottom: 0;width: 12%;display: inline-block" :prop="'templateDataList.' + index + '.appointValue'"  :rules="{ required: true,pattern:/^[+]{0,1}(\d+)$/,message: '条件必须为正整数', trigger: 'blur' }">
                          <el-input v-model="form.templateDataList[index].appointValue" placeholder="" />
                        </el-form-item>
                        <el-select v-model="form.templateDataList[index].appointType"  placeholder="" style="width: 15%">
                          <el-option
                            v-for="dict in appointTypeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                          ></el-option>
                      </el-select>包邮
                      </span>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/goods/template";
import { regionData } from 'element-china-area-data'

export default {
  name: "Template",
  data() {
    return {
      checked:true,
      regionData:regionData,
      checkAll: true,
      cities:[],
      isIndeterminate: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 模板类型 0按件计费 1按重量计费字典
      templateTypeOptions: [],
      appointTypeOptions:[],
      templateDataList:[],
      defaultProps: {
        children: 'children',
        label: 'provinceName',
        id: 'provinceCode'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
          { max: 20, message: '模板名称长度不能超过20个字符', trigger: 'blur' }
        ],
      },
      index : -1
    };
  },
  created() {
    this.getList();
    this.getCities();
    this.getDicts("template_type").then(response => {
      this.templateTypeOptions = response.data;
    });
    this.getDicts("appoint_type").then(response => {
      this.appointTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询运费模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCities(){
      this.cities=[];
      this.templateDataList = [];
      this.regionData.forEach(item=>{
        this.cities.push(item.value)
        let templateData = {
          id: null,
          extAppid: null,
          templateId: null,
          provinceCode: item.value,
          provinceName: item.label,
          type: '1',
          firstValue: null,
          firstAmount: null,
          otherValue: null,
          otherAmount: null,
          appoint: '1',
          appointValue: null,
          appointType: '0'
        };
        this.templateDataList.push(templateData)
      })
    },
    handleCheckAllChange(val) {
      if(val){
        this.form.freeCityList=this.cities;
        this.form.templateDataList = []
      }else {
        this.form.freeCityList=[];
        this.form.templateDataList = this.templateDataList
      }
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.templateDataList.forEach((item)=>{
        //如果value中包含
        if(value.indexOf(item.provinceCode) < 0){
          //如果 this.form.templateDataList不包含则添加
          const index = this.form.templateDataList.findIndex(item1 => item1.provinceCode === item.provinceCode);
          if(index < 0){
            this.form.templateDataList.push(item)
          }
        }else {
          const index = this.form.templateDataList.findIndex(item1 => item1.provinceCode === item.provinceCode);
          if(index>-1){
            this.form.templateDataList.splice(index,1)
            if(this.index == index){
              this.index = -1
            }
          }
        }
      })
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        templateName: null,
        templateType: "0",
        updateTime: null,
        freeCityList:this.cities,
        templateDataList:[]
      };
      this.index = -1;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCities();
      this.open = true;
      this.title = "添加运费模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.form.templateDataList.forEach(item=>{
          const index = this.templateDataList.findIndex(item1 => item1.provinceCode === item.provinceCode)
          if (index > -1) {
            item.provinceName=this.templateDataList[index].provinceName;
          }
        })
        this.open = true;
        this.title = "修改运费模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.index = -1;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.index = -1;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm('是否确认删除运费模板"' + row.templateName + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTemplate(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    // 节点单击事件
    handleNodeClick(data) {
      //查找index
       this.index = this.form.templateDataList.findIndex(item1 => item1.provinceCode === data.provinceCode);
      this.$refs["form"].clearValidate();
    },
  }
};
</script>
